//获取应用实例
const app = getApp();
const common = require('./../../../utils/common.js');
import { $wuxSelect } from 'weapp/index'
Page({
    data: {
        search_or_filter:1,

        active_nav_index:0,
        nav_list:[
            {label:'全部',status:1,field:"all",num:0,},
            {label:'面料',status:2,field:"fabric",num:0,},
            {label:'辅料',status:3,field:"accessories",num:0,},
            {label:'耗材',status:4,field:"commonSupplies",num:0,},
        ],
        material_list:[],
        material_total:0,
        list_params:{
            needPage:true,
            current:1   ,
            size:20,
            pages:0,
            parame:[],
            selectParame:[],
            orderBy:"",
            selectParameter:{
                color:'',
                keyword:"",
                creatDateStart:"",
                creatDateEnd:"",
                issueProcessBackingMaterial:'',
                materialTypeIds:"",
                status:"",
                supplierId:"",
                createId:"",
                storeType:"",
                tabStatus:"1",
                groupBy:"",
            }
        },
    },

    // 点击菜单
    change_nav: function (events) {
        var index = events.currentTarget.dataset.index;
        this.setData({
            active_nav_index: index,
            ["list_params.selectParameter.tabStatus"]:this.data.nav_list[index]['status'],
        });
        // 重新获取数据
        this.getSupplyList(1);
    },

    getNav(){
        common.request_api('/api/pdm/materialMasterData/getMaterialMasterDataCount',{},true,'get').then(res=>{
            let {nav_list} = this.data
            nav_list.forEach((v)=>{
                v.num = res.data[v.field] || 0
            })
            this.setData({
                nav_list,
            })
        })
    },

    clearPage(){
        this.setData({
            material_list:[],
            ["list_params.current"]:1,
            material_total:0,
        });
    },

    getSupplyList(is_clear=0){
        if(is_clear==1){
            this.clearPage();
        }
        let list_params = this.data.list_params
        let max_page = Math.ceil(this.data.material_total/list_params.size);
        
        //没数据了，拦截
        if(this.data.material_total>0 && max_page<list_params.current){
            return;
        }

        common.request_api("/api/pdm/materialMasterData/queryPage",this.data.list_params).then((res)=>{
            res.data.records.forEach((v)=>{
                let materialMainImage = v.materialMainImage
                v.materialMainImage =  `${app.globalData.alphaCdnUrl}/${materialMainImage}`;
                if(materialMainImage){
                    v.materialMainImages = [v.materialMainImage];
                }else{
                    v.materialMainImages = [];
                }
               
            })
            let material_list = this.data.material_list
            material_list.push(...res.data.records);
            this.setData({
                material_list:material_list,
                ["list_params.size"]:res.data.size,
                material_total:res.data.total,
                ["list_params.current"]:this.data.list_params.current+1,
            })
        });
    },

    onLoad: function (options) {
        this.getSupplyList();
        this.getNav();
        // 设置标题
        wx.setNavigationBarTitle({
            title: '物料列表'
        });
    },

    // 每次显示时
    onShow() {
        var __this = this;

    },
    onClick3() {
      $wuxSelect('#foo-select3').open({
        value: this.data.value3,
        multiple: true,
        toolbar: {
          title: '季节',
          confirmText: '确定',
        },
        options: [
          {
            title: '春',
            value: '春',
          },
          {
            title: '夏',
            value: '夏',
          },
          {
            title: '秋',
            value: '秋',
          },
          {
            title: '冬',
            value: '冬',
          },
        ],
        onChange: (value, index, options) => {
          console.log('onChange', value, index, options)
          this.setData({
            // value3: value,
            title3: index.map((n) => options[n].title),
          })
        },
        onConfirm: (value, index, options) => {
          this.setData({
            value3: value,
            title3: index.map((n) => options[n].title),
          })
          this.onPullDownRefresh();
        },
      })
    },
    DeleteJijie(e){
      var index = e.currentTarget.dataset.index;
      this.data.value3.splice(index, 1);
      this.setData({
          value3: this.data.value3,
      })
      // 刷新
      this.onPullDownRefresh();
    },
    template_purchase: (e) => {
        let {template_id} = e.currentTarget.dataset;
        wx.navigateTo({
            url: '/pages/material/index?template_id=' + template_id,
        })
    },
    // 页面触底时执行
    onReachBottom: function () {
        this.getSupplyList();
    },

    // 监听下拉[刷新]
    onPullDownRefresh: function () {
        this.getSupplyList(1);
        // 停止下拉
        setTimeout(() => {
            wx.stopPullDownRefresh();
        }, 1000)
    },


    // 切换展示搜索或者筛选
    search_filter_change: function (events) {
        // this.setData({
        //     search_or_filter: this.data.search_or_filter == 1 ? 2 : 1
        // })
    },

    // 搜索
    GoSearch: function (events) {
        var keywords = events.detail.value.trim();
    
        this.setData({
            ["list_params.selectParameter.keyword"]:keywords,
        })
        this.getSupplyList(1);
    },

    // 创建样板
    material_add: function (events) {
        var __this = this;
        console.log('aaaaaaaaaaaa')
        // 跳转到创建样板页面
        wx.navigateTo({
            url: '/alpha/pages/alpha_material_form/index?template_id=0',
        });
    },

    // 编辑样板
    template_update: function (events) {
        var index = events.currentTarget.dataset.index;
        var __this = this;
        // 跳转
        wx.navigateTo({
            url: '/alpha/pages/alpha_material_form/index?material_id=' + __this.data.material_list[index].id,
            events: {
                // 当修改完成时
                changeData: function (data) {

                }
            }
        });
    },

    // 跳转到详情页面
    template_detail: function (events) {
        var index = events.currentTarget.dataset.index;
        var __this = this;
        // 跳转
        wx.navigateTo({
            url: '/pages/template_detail/template_detail?template_id=' + __this.data.template_list[index].template_id,
            events: {
                // 当点击生产按钮时
                changeProductData: function (data) {
                    __this.data.template_list[index].status.value = 3;
                    __this.setData({
                        template_list: __this.data.template_list
                    })
                },
                // 当点击关闭生产按钮时
                changeCloseData: function (data) {
                    __this.data.template_list[index].status.value = 99;
                    __this.setData({
                        template_list: __this.data.template_list
                    })
                }
            }
        });
    },

    // 关闭生产
    template_close: function (events) {
        var index = events.currentTarget.dataset.index;
        var __this = this;
        // 确认提示
        wx.showModal({
            title: '提示',
            content: '您确定要关闭生产吗',
            success(res) {
                if (res.confirm) {
                    __this.template_close_request(index);
                }
            },
        });
    },

    // 关闭生产请求
    template_close_request: function (index) {
        var __this = this;
        var template_id = __this.data.template_list[index].template_id;
        var result = app.request_api('admin/template/closeTemplate', {
            id: template_id
        }, true);
        result.then(res => {
            wx.showToast({
                title: '已关闭生产',
                icon: 'none',
                duration: 2000,
            });
            // 将此数据从列表删除
            __this.data.template_list.splice(index, 1);
            __this.setData({
                template_list: __this.data.template_list
            });
        });
    },

    // 删除
    template_delete: function (events) {
        var index = events.currentTarget.dataset.index;
        var __this = this;
        // 确认提示
        wx.showModal({
            title: '提示',
            content: '您确定要删除此样板吗',
            success(res) {
                if (res.confirm) {
                    __this.template_delete_request(index);
                }
            },
        });
    },

    // 删除样板请求
    template_delete_request: function (index) {
        var __this = this;
        var template_id = __this.data.template_list[index].template_id;
        var result = app.request_api('admin/template/del', {
            ids: [template_id]
        }, true);
        result.then(res => {
            wx.showToast({
                title: '删除成功',
                icon: 'none',
                duration: 2000,
            });
            // 将此数据从列表删除
            __this.data.template_list.splice(index, 1);
            __this.setData({
                template_list: __this.data.template_list
            });
        });
    },

    // 确认生产
    template_product: function (events) {
        var index = events.currentTarget.dataset.index;
        var __this = this;
        // 确认提示
        wx.showModal({
            title: '提示',
            content: '您确定要开始生产吗',
            success(res) {
                if (res.confirm) {
                    __this.template_product_request(index);
                }
            },
        });
    },

    // 确认生产请求
    template_product_request: function (index) {
        var __this = this;
        var template_id = __this.data.template_list[index].template_id;
        var result = app.request_api('admin/template/postConfirmProduct', {
            template_id: template_id
        }, true);
        result.then(res => {
            wx.showToast({
                title: '已开始生产',
                icon: 'none',
                duration: 2000,
            });
            // 修改状态
            __this.data.template_list[index].status.value = 3;
            __this.setData({
                template_list: __this.data.template_list
            });
        });
    },

    // 预览图片
    PreviewImg: function (events) {
        var pic_arr = events.currentTarget.dataset.pic;
        // 调用
        wx.previewImage({
            current: pic_arr[0], // 当前显示图片的http链接
            urls: pic_arr // 需要预览的图片http链接列表
        })
    },

    // 生成年份
    generateYearArray: function () {
        var currentYear = new Date().getFullYear();
        var pastYears = 7;
        var futureYears = 3;
        var yearArray = [];
        // 生成过去7年的年份
        for (var i = currentYear - pastYears; i <= currentYear; i++) {
            yearArray.push(i);
        }
        // 生成未来3年的年份
        for (var j = currentYear + 1; j <= currentYear + futureYears; j++) {
            yearArray.push(j);
        }
        var currentIndex = pastYears;
        // 更新数据
        this.setData({
            yearArray: yearArray,
            currentIndex: currentIndex
        });
    },

    // 年份改变时
    yearChange: function (event) {
        var selectedYear = this.data.yearArray[event.detail.value];
        // 验证是否在数组中
        if (this.data.year.findIndex(obj => obj === selectedYear) > -1) {
            wx.showToast({
                title: '已选择过此年份',
                icon: 'none',
                duration: 1500,
            });
            return false;
        }
        this.data.year.push(selectedYear)
        this.setData({
            year: this.data.year,
        });
        // 刷新
        this.onPullDownRefresh();
    },

    // 选择类型时
    dataTypeChage: function (e) {
        this.setData({
            data_type_name: this.data.data_type_list[e.detail.value].name,
            data_type_value: this.data.data_type_list[e.detail.value].value,
        });
        // 刷新
        this.onPullDownRefresh();
    },

    // 获取分类
    get_cate_list: function () {
        // 发起请求
        var result = app.request_api('admin/processTemplate/get_category_list', {
            is_mini: 1
        }, false);
        result.then(res => {
            // console.log(res);
            if (res.list.length > 0) {
                res.list.forEach(function (item, index) {
                    // 往子项里追加全部
                    res.list[index].children.unshift({
                        id: 0,
                        category_name: '全部',
                        children: [],
                    });
                    res.list[index].children.forEach(function (item2, index2) {
                        res.list[index].children[index2].children.unshift({
                            id: 0,
                            category_name: '全部'
                        });
                    });
                });
                this.setData({
                    cate_show_data: [res.list, res.list[0].children, res.list[0].children[0].children],
                    cate_all_data: res.list
                });
            }
        });
    },

    // 分类值变化时
    CateValueChange: function (e) {
        // console.log(e);
        var cate_show_data = this.data.cate_show_data;
        var choose_index_arr = e.detail.value;
        var choose_cate_name = cate_show_data[0][choose_index_arr[0]].category_name + ' - ' + cate_show_data[1][choose_index_arr[1]].category_name + ' - ' + cate_show_data[2][choose_index_arr[2]].category_name;
        // 更新值
        this.data.choose_id_arr.push([cate_show_data[0][choose_index_arr[0]].id, cate_show_data[1][choose_index_arr[1]].id, cate_show_data[2][choose_index_arr[2]].id]);
        this.data.choose_cate_name.push(choose_cate_name);
        this.data.choose_index_arr.push(choose_index_arr);
        this.setData({
            choose_id_arr: this.data.choose_id_arr,
            choose_index_arr: this.data.choose_index_arr,
            choose_cate_name: this.data.choose_cate_name,
        });
        // 刷新
        this.onPullDownRefresh();
    },

    // 分类列变化时
    CateColumnChange: function (e) {
        var cate_all_data = this.data.cate_all_data;
        var cate_show_data = this.data.cate_show_data;
        var sel_index_arr = this.data.sel_index_arr;
        var index = e.detail.value;
        if (e.detail.column == 0) {
            // 一级分类改变时
            this.data.cate_show_data[1] = cate_all_data[index].children;
            this.data.cate_show_data[2] = cate_all_data[index].children[0].children;
            sel_index_arr = [index, 0, 0];
        }
        if (e.detail.column == 1) {
            // 二级分类改变时
            this.data.cate_show_data[2] = cate_show_data[1][index].children;
            sel_index_arr[1] = index;
            sel_index_arr[2] = 0;
        }
        if (e.detail.column == 2) {
            // 三级分类改变时
            sel_index_arr[2] = index;
        }
        // 重新渲染
        this.setData({
            cate_show_data: this.data.cate_show_data,
            sel_index_arr: sel_index_arr
        });
    },

    // 删除年份
    DeleteYear: function (e) {
        var index = e.currentTarget.dataset.index;
        // 删除对应年份
        this.data.year.splice(index, 1);
        this.setData({
            year: this.data.year,
        })
        // 刷新
        this.onPullDownRefresh();
    },

    // 删除分类
    DeleteCategory: function (e) {
        var index = e.currentTarget.dataset.index;
        this.data.choose_id_arr.splice(index, 1);
        this.data.choose_index_arr.splice(index, 1);
        this.data.choose_cate_name.splice(index, 1);
        this.setData({
            choose_id_arr: this.data.choose_id_arr,
            choose_index_arr: this.data.choose_index_arr,
            choose_cate_name: this.data.choose_cate_name,
        })
        // 刷新
        this.onPullDownRefresh();
    },

    // 删除品牌
    DeleteType: function () {
        this.setData({
            data_type_value: 0,
            data_type_name: '',
        })
        // 刷新
        this.onPullDownRefresh();
    },

})
